package com.hjy.controller;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "TimeController", value = "/time")
public class TimeController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        Cookie[] cookies = request.getCookies();
        //判断是否有lastLoginTime这个cookie
        boolean flag = false;
        long time = 0;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("lastLoginTime")){
                flag = true;
                time =Long.parseLong(cookie.getValue());
                break;
            }
        }
        //有和没有的区别
        PrintWriter writer = response.getWriter();
        if (flag==true){
            Date date = new Date(time);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format(date);
            writer.write("您的上一次访问时间是:"+format );
        }else {
            writer.write("这是您第一次访问该网站");
        }
        //修改这个cookie的信息
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        Cookie cookie1 = new Cookie("name", "骏扬");
        response.addCookie(cookie1);
        //以秒为单位
        cookie.setMaxAge(60*60*24);
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
